<template>
    <el-card shadow="never" style="margin-top: 16px">
        <div class="title">
            <p>{{ props.title }}</p>
        </div>

        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="触达状态">
                <el-select v-model="region" size="small" @change="handleReach">
                    <el-option v-for="item in reach" :key="item.id" :label="item.label" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <div>
                    <el-button size="small" @click="exportDetails">导出明细</el-button>
                    <el-button
                        v-if="props.type == 1"
                        size="small"
                        :disabled="select_list2.length == 0"
                        @click="batchAllot"
                        >批量分配</el-button
                    >
                    <el-button size="small" :disabled="select_list.length == 0" @click="sendMesg">批量发送</el-button>
                </div>
            </el-form-item>
        </el-form>
        <ZwTable
            ref="tableRef"
            is-limit-height
            class="table-box"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()"
            @select-all="onSelectAll"
            @select="onSelect">
        </ZwTable>
    </el-card>
    <el-drawer v-model="drawer" custom-class="draOut" :title="title" size="25%" @close="handleClose">
        <el-scrollbar class="scrollbar">
            <div class="preview">
                <div class="prev_box">
                    <div class="phone_con">
                        <el-scrollbar class="phone_List">
                            <Friend ref="friend" :friend-detail="FriendDetail" />
                        </el-scrollbar>
                    </div>
                </div>
            </div>
        </el-scrollbar>
    </el-drawer>
    <ZWDepart ref="DepartRef" :model:show="true" @submit="getDepart" />
</template>

<script lang="tsx" setup>
import { computed, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import Friend from './Friend.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { qwView, batchSend } from '@/api/smartMarketing/precision/stat';
import { batchAllots } from '@/api/employe/staffsupervision/deletrecord';
import { deepCopy } from '@/utils/helper';
import { baseInfo, census, addShop, expDetails } from '@/api/smartMarketing/precision/stat';
import { getVideoImage, getSetionId } from '@/utils/utils';
import ZwTable from '@/components/zw/table/Table';
import { ElMessage, ElPopover, ElImage, ElIcon, ElButton } from 'element-plus';
import { div } from '@/utils/math';

const emit = defineEmits(['export', 'submit', 'send']);
const props = defineProps(['title', 'type', 'info', 'reach', 'viewId', 'tableParams']);

const DepartRef = ref();
const route = useRoute();

const tableRef: any = ref(null);
const FriendDetail = ref();
const tableData = ref([]);
const region = ref(0);
const drawer = ref(false);
// eslint-disable-next-line vue/no-dupe-keys
const title = ref('');
const select_list = ref([]);
const select_list2 = ref([]);
const creators = ref([]);
const prams = reactive({
    touch_type: props.type,
    touch_status: region.value,
    page: 1,
    page_size: 15
});

const tableOption = computed(() => {
    const arr = [
        {
            type: 'selection',
            width: 55,
            fixed: 'left'
        },
        {
            label: '客户信息',
            width: 180,
            render({ row, column, index }) {
                const slotReference = () => (
                    <p class="info">
                        <span class="info_name">{row.cust_info.name}</span> &nbsp;{' '}
                        <span vShow={row.cust_info.nickname}>|</span> &nbsp;{' '}
                        <span class="info_name">{row.cust_info.nickname}</span>
                    </p>
                );
                const slotDefault = () => (
                    <p class="info">
                        <span>{row.cust_info.name}</span> &nbsp;<span vShow={row.cust_info.nickname}>|</span>&nbsp;{' '}
                        <span>{row.cust_info.nickname}</span>
                    </p>
                );
                const slotError = () => (
                    <div class="image_slot">
                        <ElIcon>
                            <IconPicture />
                        </ElIcon>
                    </div>
                );
                return (
                    <div class="custInfo">
                        <ElImage
                            class="custInfo_avatar"
                            vSlots={{ error: slotError }}
                            src={row.cust_info.avatar}
                            fit="cover"
                            class="avatar"></ElImage>
                        <ElPopover
                            placement="top-start"
                            popper-class="popGroup"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width="auto"></ElPopover>
                    </div>
                );
            }
        },
        {
            prop: 'mobile',
            label: '客户手机',
            width: 140,
            render({ row }) {
                return <span>{row.cust_info.mobile}</span>;
            }
        },
        {
            prop: 'touch_type_name',
            label: '触达方式',
            width: 100,
            render({ row }) {
                return <span>{row.touch_type_name}</span>;
            }
        },
        {
            prop: 'touch_type_name',
            label: props.type == 2 ? '短信内容' : '标题内容',
            render({ row }) {
                const slotReference = () => (
                    <p class="message">
                        {props.type == 2
                            ? row.sms_content
                                ? row.sms_content
                                : '--'
                            : row.task_title
                            ? row.task_title
                            : '--'}
                    </p>
                );
                const slotDefault = () => (
                    <p>
                        {props.type == 2
                            ? row.sms_content
                                ? row.sms_content
                                : '--'
                            : row.task_title
                            ? row.task_title
                            : '--'}
                    </p>
                );
                return (
                    <div>
                        <ElPopover
                            placement="top-start"
                            popper-class="popGroup"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width={300}></ElPopover>
                    </div>
                );
            }
        },
        {
            prop: 'touch_type_name',
            label: '任务内容',
            width: 80,
            render({ row }) {
                return (
                    <ElButton type="text" link onClick={() => preview(row)}>
                        预览
                    </ElButton>
                );
            }
        },
        {
            prop: 'belong_work_user_name',
            label: '归属员工',
            width: 80,
            render({ row }) {
                return <p>{row.cust_info.belong_work_user_name}</p>;
            }
        },
        {
            prop: 'send_status_name',
            label: props.type == 2 ? '发送状态' : '执行状态',
            width: 100,
            render({ row }) {
                return <span>{row.send_status_name || '--'}</span>;
            }
        },
        {
            prop: 'touch_type_name',
            label: '原因',
            width: 245,
            render({ row }) {
                const slotReference = () => <p class="message">{row.fail_reason || '--'}</p>;
                const slotDefault = () => <p>{row.fail_reason || '--'}</p>;
                return (
                    <div>
                        <div vShow={row.fail_reason}>
                            <ElPopover
                                placement="top-start"
                                popper-class="popGroup"
                                trigger="hover"
                                vSlots={{ reference: slotReference, default: slotDefault }}
                                width={300}></ElPopover>
                        </div>
                        <span vShow={!row.fail_reason}>--</span>
                    </div>
                );
            }
        },
        {
            prop: 'send_time',
            label: '发送时间',
            width: 180,
            render({ row }) {
                return <span>{row.send_time || '--'}</span>;
            }
        },
        {
            prop: 'operate',
            label: '操作',
            width: 190,
            fixed: 'right',
            isOperate: true,
            renderOperate({ row, column, index }) {
                return (
                    <div>
                        <ElButton vShow={props.type == 1} size="small" onClick={() => batchAllot(row, 1)}>
                            分配员工
                        </ElButton>
                        <ElButton
                            vShow={props.type == 2 && row.send_status != 2}
                            size="small"
                            onClick={() => batchAllot(row, 1)}>
                            再次发送
                        </ElButton>
                        <ElButton vShow={row.send_status != 2} size="small" onClick={() => sendMesg(row, 1)}>
                            重新发送
                        </ElButton>
                    </div>
                );
            }
        }
    ];
    if (props.type == 2) {
        arr.splice(5, 2);
    }
    return arr;
});
const getRowKey = (row: any) => {
    return row.id;
};
const defaultParams = reactive({});
const state = reactive({
    searchParams: deepCopy({ ...defaultParams, ...props.tableParams })
});
const fetchApi = () => {
    return addShop;
};

const onExport = () => {
    emit('export', props.type);
};
// 筛选触发条件
const handleReach = () => {
    prams.touch_status = region.value;
    state.searchParams.touch_status = region.value;
};
// 分页数据
const getData = (data: any) => {
    prams.page = data.page;
    prams.page_size = data.page_size;
    emit('submit', prams);
};
// 导出明细
const exportDetails = () => {
    emit('export', { touch_type: props.type, touch_status: region.value });
};
const getDepart = (data: any) => {
    const params = {
        customer_list: Array.from(new Set(select_list2.value)),
        work_user_list: getSetionId('id', data)
    };
    data.length &&
        batchAllots(params).then(() => {
            ElMessage.success('分配成功！');
            emit('send', { touch_type: props.type, touch_status: region.value });
        });
};
// 分配
const batchAllot = (row: any, num: number) => {
    DepartRef.value.appDialog.title = '分配员工';
    DepartRef.value.departVisble = true;
    DepartRef.value.isMember = true;
    DepartRef.value.selectedMember = [];
    if (num == 1 && num) {
        select_list2.value = [row.cust_id];
    }
};
const fun = (p: object) => {
    batchSend(p).then(() => {
        ElMessage.success('发送成功！');
        select_list.value = [];
        emit('send', { touch_type: props.type, touch_status: region.value });
    });
};
// 再次发送
const sendMesg = (row?: any, num?: number) => {
    if (num == 1 && num) {
        fun({ touch_type: props.type, task_ids: [row.id], market_rule_id: route.query.id });
    } else {
        fun({ touch_type: props.type, task_ids: select_list.value, market_rule_id: route.query.id });
    }
};
// 预览
const preview = (row: any) => {
    qwView({ basic_word_id: props.viewId }).then((res: any) => {
        drawer.value = true;
        getPhoneData(res.welcome_info.welcome_material, res.welcome_info.welcome_text);
    });
    title.value = `预览${row.cust_info.name}的营销任务`;
};
const handleClose = () => {
    drawer.value = false;
};

/**
 * 欢迎语数据转换phone展示
 * @param data array格式
 * @param content 文本内容
 */
const getPhoneData = (data: any[], content?: string) => {
    const arr: any[] = [];
    if (content) {
        arr.push({
            type: 0,
            content: content
        });
    }
    if (data.length > 0) {
        data.forEach((item: any) => {
            const obj = {
                type: 0,
                absolute_url: '',
                name: '',
                title: '',
                content: '',
                cover_image_url: '',
                file_size: '',
                user_name: '',
                mediaFileInfo: {
                    size: 0
                }
            };
            // 图片
            if (item.type == 1) {
                obj.type = 1;
                obj.absolute_url = item.absolute_url;
            }
            // 视频
            if (item.type == 2) {
                obj.type = 2;
                obj.thumbnail_url = getVideoImage(item.absolute_url, 80, 55);
            }
            // 链接
            if (item.type == 3) {
                obj.type = 3;
                obj.title = item.link_title;
                obj.cover_image_url = item.link_share_image;
            }
            // 音频
            if (item.type == 4) {
                obj.type = 4;
                obj.title = item.name;
                obj.file_size = item.size;
            }
            // 文件
            if (item.type == 5) {
                obj.type = 5;
                obj.name = item.name;
                obj.mediaFileInfo.size = item.size;
            }
            // 活动
            if (item.type == 6) {
                obj.type = 6;
                obj.title = item.link_title;
                obj.cover_image_url = item.link_share_image;
            }
            //电商素材-商品素材
            if (item.type == 7) {
                obj.type = item.type;
                obj.name = item.link_title;
                obj.cover_image_url = item.link_share_image;
            }
            //收集表
            if (item.type == 9) {
                obj.type = item.type;
                obj.name = item.link_title;
                obj.cover_image_url = item.link_share_image;
            }
            //公众号图文
            if (item.type == 10) {
                obj.type = item.type;
                obj.name = item.link_title;
                obj.cover_image_url = item.link_share_image;
            }
            //小程序
            if (item.type == 11) {
                obj.type = 11;
                obj.title = item.title;
                obj.cover_image_url = item.absolute_url;
            }
            arr.push(obj);
        });
    }
    FriendDetail.value = arr;
};
const onLoad = () => {
    state.searchParams = deepCopy({ ...defaultParams, ...props.tableParams });
};
// onLoad()
watch(
    () => props.info,
    val => {
        tableData.value = val;
    }
);
defineExpose({
    onLoad
});
</script>
<style lang="scss" scoped>
.el-form {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-form-item {
        margin-bottom: 14px;
    }
}

.title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 14px;
    margin-bottom: 21px;
    border-bottom: 1px solid #eaeaea;
    font-size: 16px;
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-weight: 400;
    color: #35383a;
}

:deep(.custInfo) {
    display: flex;
    align-items: center;

    .custInfo_avatar {
        width: 36px;
        height: 36px;
        margin-right: 12px;
        border-radius: 4px;

        .image-slot {
            width: 100%;
            height: 100%;
        }
    }

    .info {
        display: flex;
        align-items: center;

        &_name {
            display: inline-block;
            max-width: 50px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }
    }
}

:deep(.message) {
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    overflow: hidden;

    /*! autoprefixer: off */
    -webkit-box-orient: vertical;
}

.product {
    display: flex;
    align-items: center;

    .cover {
        width: 40px;
        height: 40px;
        margin-right: 8px;
    }

    .info {
        font-weight: 300;
        font-family: STHeitiSC-Light, STHeitiSC;

        .product_name {
            height: 20px;
            font-size: 14px;
            color: #33302d;
            line-height: 14px;
        }

        .description {
            width: 432px;
            height: 12px;
            font-size: 12px;
            font-weight: 300;
            color: #969696;
            line-height: 12px;
        }
    }

    .image-slot {
        width: 100%;
        height: 100%;
    }
}

.empty {
    margin: 100px 0;

    .empty_img {
        transform: translateX(13%);
    }
}

:deep(.draOut) {
    position: relative;
}

.scrollbar {
    height: calc(100vh - 150px);
    overflow-y: auto;
}

.preview {
    overflow: hidden;

    .prev_box {
        flex: 1;

        .phone_con {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 244px;
            height: 495px;
            box-sizing: border-box;
            border-radius: 36px;
            border: 9px solid #eef5fe;
            background: url('@/assets/image/channel/phone_bg.png');
            background-size: cover;

            .phone_List {
                width: 100%;
                box-sizing: border-box;
                position: absolute;
                top: 48px;
                height: 380px;
                bottom: 48px;
                padding: 7px 10px;
            }
        }
    }

    .pre_list {
        margin: 15px 30px;
        width: 370px;
        overflow: auto;
        background: #f7f7f7;
        border-radius: 1px;
        padding-left: 20px;
        padding-bottom: 1px;
        box-sizing: border-box;

        .pre_main {
            padding-top: 12px;

            .pre_list_item {
                margin-bottom: 16px;
                display: flex;
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                text-align: left;

                .pre_item_con {
                    flex: 1;
                    color: #33302d;
                }
            }

            .pre_item_label {
                margin-bottom: 16px;
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                display: flex;

                .item_name {
                    display: flex;
                    flex-direction: column;

                    .bg_name:nth-child(n + 2) {
                        margin-top: 10px;
                    }
                }
            }

            .send_box {
                display: flex;
                width: 100%;
                font-size: 12px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                transform: scale(0.83);
                transform-origin: left top;
                margin-bottom: 4px;
                color: #33302d;

                .send_box_name {
                    display: inline-block;
                    width: 98px;
                }
            }
        }
    }
}
</style>
